package akka.scala

import akka.actor.{Actor, ActorSystem, PoisonPill, Props}

/**
  * Created by liuwei on 2017/5/10.
  */

case class CreateChild (name: String)
case class Name (name: String)

class Child extends Actor {
  var name = "No name"

  /**
    *  关闭文件或数据库连接
    */
  override def postStop: Unit = {
    println(s"D'oh! They killed me ($name): ${self.path}")
  }
  def receive = {
    case Name(name) => this.name = name
    case _ => println(s"Child $name got message.")
  }
}

class Parent extends Actor {
  def receive = {
    case CreateChild(name) =>
      // Parent creates a new Child here
      println(s"Parent about to create Child ($name) ...")
      //创建子actor
      val child = context.actorOf(Props[Child], name=s"$name")
      child ! Name(name)
    case _ => println(s"Parent got some other message.")
  }
}

object ParentChildDemo extends App{
  val actorSystem = ActorSystem("ParentChildTest")
  val parent = actorSystem.actorOf(Props[Parent], name="Parent")

  // send messages to Parent to create to child actors
  parent ! CreateChild("XiaoMing")
  parent ! CreateChild("XiaoLiang")
  Thread.sleep(500)

  // lookup XiaoMing, the kill it
  println("Sending XiaoMing a PoisonPill ... ")
  val xiaoming = actorSystem.actorSelection("/user/Parent/XiaoMing")
  /**
    * PoisonPill和gracefulStop
还有其他两种方式，发送PoisonPill消息或者使用gracefulStop终止。
你也可以向actor发送akka.actor.PoisonPill消息,这个消息处理完成后actor会被终止。PoisonPill与普通消息一样被放进队列，因此会在已经入队列的其它消息之后被执行。
    */
  xiaoming ! PoisonPill
  println("XiaoMing was killed")

  Thread.sleep(5000)
  actorSystem.terminate()
}